package client;

import httpMessage.HttpRequest;
import httpMessage.HttpResponse;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import error.NoConnectionException;

public class HttpClient {

	private String basicRequest = "GET / HTTP/1.1 \n Host: localhost:4444 \n User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:7.0.1) Gecko/20100101 Firefox/7.0.1 \nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\nAccept-Language: en-us,en;q=0.5\nAccept-Encoding: gzip, deflate\nAccept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\nConnection: keep-alive";

	private Socket clientSocket;
	private String hostname;

	public HttpClient(int portnr, String hostname) throws NoConnectionException {
		this.hostname = hostname;
		try {
			clientSocket = new Socket(hostname, portnr);
			System.out.println("Connected to " + hostname + " with portnr: "
					+ portnr);
		} catch (UnknownHostException e) {
			System.out.println("Host" + hostname + " not found");
			throw new NoConnectionException();
		} catch (IOException e) {
			System.out.println("Could no open connection on port: " + portnr);
			throw new NoConnectionException();
		}
	}

	public void downloadFile(String url) {
		byte[] data = sendGETRequest(url);

		if (url.equals("/"))
			url = "index.html";
		url = hostname + "/" + url;

		String dirs[] = url.split("/");
		String dirpath = "";
		for (int i = 0; i < dirs.length - 1; i++) {
			dirpath += dirs[i] + "/";
		}
		System.out.println(dirpath);
		new File(dirpath).mkdirs();

		File file = new File(url);
		try {
			FileOutputStream out = new FileOutputStream(file);
			out.write(data);
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public byte[] sendGETRequest(String url) {
		try {
			DataOutputStream toServer = new DataOutputStream(
					clientSocket.getOutputStream());
			System.out.println("Request:");

			HttpRequest request = new HttpRequest(url, "GET", hostname);
			System.out.println();
			System.out.println(request);
			System.out.println();

			toServer.write(request.toString().getBytes("UTF-8"));
			toServer.flush();

			clientSocket.shutdownOutput();
			System.out.println("Response:");
			System.out.println();
			InputStream in = clientSocket.getInputStream();

			ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int length = 0;

			while ((length = in.read(buffer)) != -1) {
				dataStream.write(buffer, 0, length);
			}

			byte[] data = dataStream.toByteArray();

			// eerst response headers inlezen
			String dataStr = new String(data, "UTF-8");
			HttpResponse response = new HttpResponse(dataStr);
			System.out.println(dataStr);

			if (response.getStatuscode().contains("404"))
				System.out.println("Error 404 : file not found");
			// System.out.println( data );

			// daarna data inlezen
			Pattern p = Pattern.compile("\r\n\r\n");
			Matcher m = p.matcher(dataStr);
			int startdata = 0;
			if (m.find()) {
				startdata = m.end();
			}

			System.out.println("Total size : " + data.length + " data starts @"
					+ startdata);
			System.out.println("Body size : " + (data.length - startdata));

			byte[] messageBody = new byte[response.getSize()];
			System.arraycopy(data, startdata, messageBody, 0, data.length
					- startdata);

			in.close();
			toServer.close();
			clientSocket.close();
			return messageBody;
		} catch (IOException e) {
			System.out.println("Packet sending failed");
			e.printStackTrace();
		}
		return null;
	}
}
